
layui.use(['form', 'layer', 'table'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var handle_url = $('.handle_url').val();
    var check_name_url = $('.check_name_url').val();

    var img_urls_url = $('.img_urls_url').val();
    var detections_url = $('.detections_url').val();
    var cookbooks_url = $('.cookbooks_url').val();

    var cerate_bar_code_url = $('.cerate_bar_code_url').val();
    var cerate_fresh_code_url = $('.cerate_fresh_code_url').val();
    var cerate_plu_code_url = $('.cerate_plu_code_url').val();


    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 50,
        limits : [20, 30, 50, 100, 200],
        id : "tableList",
        /*initSort: {
            field: 'price' // 排序字段，对应 cols 设定的各字段名
            ,type: 'asc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        },*/
        cols : [[
            /*{type: "checkbox", fixed:"left", width:50},*/
            {field: 'id', title: '序号', minWidth:140},
            {field: 'img_url', title: '封面图', minWidth:80, align:"center", templet:function(data){
                return '<a href="'+data.img_url+'" target="_blank"><img src="'+data.img_url+'" style="width: 80px;" /></a>';
            }},
            {field: 'name', title: '商品名称', minWidth:140},
            {field: 'spec', title: '规格', align:'center'},
            {field: 'bar_code', title: '条码', align:'center', minWidth:140},
            {field: 'category_id', title: '分类', align:'center'},
            {field: 'unit', title: '单位', align:'center'},
            {field: 'purchase_price', title: '进货价', align:'center', templet:function(data){
                return data.purchase_price / 100;
            }},
            {field: 'price', title: '售价', align:'center', sort: true, templet:function(data){
                return data.price / 100;
            }},
            {field: 'wholesale_price', title: '批发价', align:'center', templet:function(data){
                return data.wholesale_price / 100;
            }},
            {field: 'supplier_id', title: '供货商', align:'center'},
            /*{field: 'isActive', title: '是否上架', align:'center', templet:function(data){
                if (data.status == 1) {
                    return '<span class="layui-btn layui-btn-green layui-btn-xs">上架</span>'
                } else {
                    return '<span class="layui-btn layui-btn-danger layui-btn-xs">下架</span>'
                }
            }},*/
            {field: 'create_date', title: '添加时间', align:'center', minWidth:110, sort: true},
            {field: 'status', title: '状态', align:"center", templet:function(data){
                var html = '';
                if (data.status == 1) {
                    html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'" checked>';
                } else {
                    html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'">';
                }

                return html;
            }},
            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/
            {title: '操作', fixed:"right", align:"center", minWidth:200, templet:function(data){
                var html = '';
                    //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                if (data.status == 1) {
                    html += '<button type="button" class="layui-btn layui-btn-xs layui-btn-warm" lay-event="qr_code">二维码</button>';
                }

                return html;
            }}
        ]],
        done: function(res, curr, count){
            // 如果是异步请求数据方式，res即为你接口返回的信息。
            // 如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            //console.log(res);
            // 得到当前页码
            //console.log(curr);
            // 得到数据总量
            //console.log(count);
            var data = res.data;

            for(var i=0; i<data.length; i++){
                console.log(data[i].status);
                if (data[i].status == 2) {
                    var index = res.data[i]['LAY_TABLE_INDEX'];
                    $('tr[data-index=' + index + ']').find('.layui-table-cell').css('color', 'red');
                }
            }
        }
    });

    // 搜索
    $(".search_btn").on("click", function(){
        var name = $('.searchBox').find('input[name=name]').val();
        var category_id = $('.searchBox').find('select[name=category_id]').val();
        var supplier_id = $('.searchBox').find('select[name=supplier_id]').val();
        var price_type = $('.searchBox').find('select[name=price_type]').val();

        if(name != '' || category_id != '' || supplier_id != '' || price_type != ''){
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: name,
                    category_id: category_id,
                    supplier_id: supplier_id,
                    price_type: price_type,
                }
            });
        }else{
            layer.msg("请选择筛选条件");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function(){
        table.reload("tableList", {
            where: {
                name: '',
                category_id: '',
                supplier_id: '',
                price_type: '',
            }
        });
    });

    // 批量删除
    $(".delAll_btn").on("click", function(){
        var checkStatus = table.checkStatus('tableList'),
            data = checkStatus.data,
            ids = [];
        if(data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            layer.confirm('确定删除选中的数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"ids": ids},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('删除成功', {icon: 1});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的数据");
        }
    });

    // Status 操作
    form.on('switch(status)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});

        var status = 2;
        if(data.elem.checked){
            status = 1;
        }

        $.ajax({
            url: handle_url,
            data: {'id' : data.elem.value,'status' : status},
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if (res.code == 1) {
                    parent.layui.table.reload('tableList', {});
                } else {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit') {
            formHtml(data);
        } else if(layEvent === 'qr_code') {
            // 商品二维码
            var qrCode = obj.data.qr_code;
            var protocol = window.location.protocol;
            //var host = 'http://' + window.location.host;
            var host = protocol + '//' + window.location.host;
            var imgUrl = host+'/public/upload/'+qrCode;

            var title = '商品二维码';
            var confirmBtn = '下载二维码';
            var content = '<img src="'+imgUrl+'" alt="商品二维码">';
            layer.open({
                title: title,
                area: ['380px', '450px'],
                content: content,
                btn: [confirmBtn],
                btnAlign: 'c', //按钮居中
                yes: function(index){
                    download(imgUrl);
                    layer.close(index);
                }
            });
        }
    });

    // 文件下载
    var download = function (src) {
        var $a = document.createElement('a');
        $a.setAttribute("href", src);
        $a.setAttribute("download", "");
        var evObj = document.createEvent('MouseEvents');
        evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
        $a.dispatchEvent(evObj);
    };

    // 删除
    /*$('.del-btn').on('click', function(){
        layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
            $.ajax({
                url: delete_url,
                data: {"id": data.id},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        layer.msg('已删除', {icon: 1, time: 1000});
                        tableIns.reload();
                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
        });
    });*/

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: 5
            , id: 'product_iframe'
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.2
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '800px'
            , top: 0
            , content: content
        });
    }

    // 生成条码
    $('.bar_code-btn').on('click', function(){
        $.get(cerate_bar_code_url, function(res){
            if (res.code == 1) {
                $('input[name=bar_code]').val(res.data);
            } else {
                layer.msg(res.msg);
            }
        });
    });
    // 生成生鲜码
    $('.fresh_code-btn').on('click', function(){
        $.get(cerate_fresh_code_url, function(res){
            if (res.code == 1) {
                $('input[name=fresh_code]').val(res.data);
            } else {
                layer.msg(res.msg);
            }
        });
    });
    // 生成PLU码
    $('.plu_code-btn').on('click', function(){
        $.get(cerate_plu_code_url, function(res){
            if (res.code == 1) {
                $('input[name=plu_code]').val(res.data);
            } else {
                layer.msg(res.msg);
            }
        });
    });

    // 批量导出
    $('#export_csv').on('click', function(){
        var url = $(this).data('url');
        var name = $('.searchBox').find('input[name=name]').val();

        var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
        $form += '<input name="name" value="'+name+'" >';
        $form += '</form>';
        if($(document).find('#export_form').length){
            $(document).find('#export_form').remove();
        }
        $(document.body).append($form);
        // 提交表单，实现下载
        $(document).find('#export_form').submit();
    });

    // 自定义验证规则
    form.verify({
        name: function(value){
            if(value == ''){
                return '商品名不能为空';
            }
            if(value.length > 40){
                return '商品名最多为40个字符';
            }
        },
        img_url: function(value){
            if(value == ''){
                return '请上传商品图';
            }
        },
        price: function(value){
            if(value.trim() == ''){
                return '售价不能为空';
            }
            if(!/^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(value)){
                return '售价格式不正确，应为正整数，或者小数点后只有两位的小数';
            }
            if(value <= 0){
                return '售价应大于0';
            }
        },
        purchase_price: function(value){
            if (value.trim() == '') {
                //return '进价不能为空';
            } else {
                if(!/^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(value)){
                    return '进价格式不正确，应为正整数，或者小数点后只有两位的小数';
                }
                if(value <= 0){
                    //return '进价应大于0';
                }
            }
        },
        wholesale_price: function(value){
            if (value.trim() == '') {
                //return '批发价不能为空';
            } else {
                if(!/^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(value)){
                    return '批发价格式不正确，应为正整数，或者小数点后只有两位的小数';
                }
                if(value <= 0){
                    //return '批发价应大于0';
                }
            }
        },
        lowest_price: function(value){
            if(value.trim() == ''){
                return '最低售价不能为空';
            }
            if(!/^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(value)){
                return '最低售价格式不正确，应为正整数，或者小数点后只有两位的小数';
            }
            if(value <= 0){
                //return '最低售价应大于0';
            }
        },
        member_integral: function(value){
            if (value == '' || value == 0) {
                //return '会员积分不能为空';
            } else {
                if(!/^\+?[1-9][0-9]*$/.test(value)){
                    return '会员积分格式不正确，应为大于0的正整数';
                }
            }
        },
        fresh_code: function(value){
            if ($('.price_type').val() == 2) {
                if (value == '') {
                    return '请生成生鲜码';
                }
                if (!/^\d{5}$/.test(value)) {
                    return '生鲜码格式不正确';
                }
            }
        },
        plu_code: function(value){
            if ($('.price_type').val() == 2) {
                if (value == '') {
                    return '请生成PLU码';
                }
                if (!/^\d{4}$/.test(value)) {
                    return 'PLU码格式不正确';
                }
            }
        },
        /*store_count: function(value){
            if (value == '') {

            } else {
                if(!/^\+?[1-9][0-9]*$/.test(value)){
                    return '初始库存格式不正确，应为大于0的正整数';
                }
            }
        },*/
        upper_store_count: function(value){
            if (value == '') {
                return '库存上限不能为空';
            } else {
                if(!/^\+?[1-9][0-9]*$/.test(value)){
                    return '库存上限格式不正确，应为大于0的正整数';
                }
            }
        },
        lower_store_count: function(value){
            if (value == '') {
                return '库存下限不能为空';
            } else {
                if(!/^\+?[1-9][0-9]*$/.test(value)){
                    return '库存下限格式不正确，应为大于0的正整数';
                }
            }
        },
        weight: function(value){
            if ($('.sales_way[value=2]').is(':checked')) {
                if (value == '') {
                    return '请输入重量';
                }
                if (value <= 0) {
                    return '重量应大于0';
                }
            }
        },
        quality_time: function(value){
            if (value == '' || value == 0) {

            } else {
                if(!/^\+?[1-9][0-9]*$/.test(value)){
                    return '保质期格式不正确，应为大于0的正整数';
                }
            }
        },
    });

    // 表单提交
    form.on("submit(laySave)", function(data){
        var sales_way_len = $("input[name^='sales_way']:checked").length;
        if(sales_way_len <= 0){
            layer.msg('请至少选择一个销售方式！', {icon: 5});
            return false;
        }

        if(data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }
        // 是否开启退款
        if(data.field.after_sale_type == 'on') {
            data.field.after_sale_type = 1;
        } else {
            data.field.after_sale_type = 2;
        }
        // 是否开启退货
        if(data.field.is_returned == 'on') {
            data.field.is_returned = 1;
        } else {
            data.field.is_returned = 2;
        }
        // 计价方式
        if(data.field.price_type != 2) {
            data.field.fresh_code = '';
            data.field.plu_code = '';
        }

        var name = $('#name').val();
        var ori_name = $('#name').attr('data-name');

        if(name != ori_name){
            var url = check_name_url;
            $.ajax({
                url: url,
                type: 'POST',
                data: {'name': name},
                dataType : 'json',
                success: function (res) {
                    if(res.status == 1){
                        layer.msg('该商品名已经存在！', {icon: 5});
                        $('#name').focus();
                        return false;
                    }else{
                        submitForm(data);
                    }
                }
            });
            return false;
        }

        submitForm(data);
    });

    // 表单提交
    function submitForm(data){
        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    layer.closeAll("iframe");
                    parent.layui.table.reload('tableList', {});
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    }

    // 展示图片
    $('#view-img_urls').on('click', function(){
        var content = img_urls_url;
        var index = layer.open({
            title : "图片管理",
            type : 2,
            area : ["800px", "600px"],
            content : content,
            success : function(layero, index){
                form.render();
            }
        });
        //layer.full(index);
    });

    // 检测报告
    $('.view-detections').on('click', function(){
        var content = detections_url;
        /*if ($('input[name=id]').val()) {
            content += '?id=' + $('input[name=id]').val();
        } else {
            content += '?detections=' + $('.detections').val();
        }*/
        var index = layer.open({
            title : "检测报告",
            type : 2,
            area : ["800px", "600px"],
            content : content,
            success : function(layero, index){
                form.render();
            }
        });
        //layer.full(index);
    });

    // 菜谱
    $('.view-cookbook').on('click', function(){
        var content = cookbooks_url;
        /*if ($('input[name=id]').val()) {
            content += '?id=' + $('input[name=id]').val();
        } else {
            content += '?cookbook_ids=' + $('.cookbook_ids').val();
        }*/
        // var index = layer.open({
        //     title : "菜谱",
        //     type : 2,
        //     area : ["800px", "600px"],
        //     content : content,
        //     success : function(layero, index){
        //         form.render();
        //     }
        // });
        //layer.full(index);
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: -1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.1
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '800px'
            , top: 0
            , content: content
            , success: function () {
                //init_laydate(); // 不生效
            }
        });
    });


    //++ 七牛上传初始化 Begin ++//
    var token_url = $('.token_url').val();
    var record_url = $('.record_url').val();
    var upload_element = 'upload-video';
    var upload_btn = 'upload-video-btn';
    var max_file_size = '5MB';
    var extensions = 'mp4';
    var multi = true;
    var initUploaderVideo = function () {
        $.ajax({
            url: token_url,
            type: 'POST',
            data: {},
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType : 'json',
            success: function (data) {
                var url = "";
                var qiniupercent = "";
                var uploader = upload_element;
                var pickfiles = upload_btn;

                uploaderReadyForVideo(data.uptoken, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi);
            }
        });
    };
    var uploaderReadyForVideo = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            container: uploader,      //上传按钮的上级元素ID
            drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                var $item = '';
                                $item += '<span class="multi-image">';
                                $item += '<input type="hidden" name="video_ids" value="'+data.image_id+'">';
                                $item += '<input type="hidden" name="videos[]" value="'+sourceLink+'">';
                                $item += '<video class="img-responsive" name="img_qiniu_url" src="'+sourceLink+'" />  <source name="img_qiniu_url"  class="img-responsive" src="'+sourceLink+'"  type="video/mp4" /> </video>';
                                $item += '<img class="del" src="/public/static/admin/pages/image/del.png" alt="">';
                                $item += '</span>';

                                $('#' + upload_btn).before($item);
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };
    // 删除原图
    var delOriginalImg = function (img_id, img_url) {
        var delimage_url = $('.delimage_url').val();

        $.ajax({
            url: delimage_url,
            type: 'POST',
            data: {
                'imgUrl' : img_url,
                'id' : img_id
            },
            cache: false,
            dataType : 'json',
            success: function (data) {
                //
            }
        });
    };
    //++ 七牛上传初始化 End ++//

    if($('#upload-video').length > 0){
        initUploaderVideo();
    }

});